#include "LogoScene.h"
#include "TextureManager.h"
#include <vector>


LogoScene::LogoScene(const std::string &logoFilename, const sf::Color &backgroundColor, float fadeTime, float logoTime,int nCols,int nRows,float frameTime,float nScaleX,float nScaleY)
{
	this->logoFilename = logoFilename;
	this->backgroundColor = backgroundColor;	
	this->fadeTime = fadeTime;
	this->logoTime = logoTime;
	this->nCols=nCols;
	this->nRows=nRows;
	this->frameTime=frameTime;
	this->nScaleX=nScaleX;
	this->nScaleY=nScaleY;
	totalElapsedTime = 0;
	logoSprite = new AnimatedSprite(logoFilename,nCols,nRows);
	
}

void LogoScene::Init(){	
		
	vista =theEngine.GetRenderWindow().GetDefaultView();
	
	if(nCols>1) //Si se trata de un SpriteAnimado con Frames
	{
	std::vector< std::vector <unsigned> > frames;
	frames.push_back(std::vector<unsigned>()); // insertamos el vector dentro del vector de vectores
	for(int n=0;n<nCols;n++)
	{
	frames[0].push_back(n);    
	}		
	logoSprite->SetAnimation(frames[0],frameTime);
	}
	logoSprite->SetCenter((logoSprite->GetImage()->GetWidth()/nCols)/2.0f,(logoSprite->GetImage()->GetHeight()/nRows)/2.0f); //---*Calculamos el centro del AnimatedSprite
	logoSprite->SetScale(nScaleX,nScaleY);                                                                                   //---*Lo Escalamos.
	logoSprite->SetPosition(vista.GetHalfSize().x,vista.GetHalfSize().y);                                                    //---*Le damos Posicion.
}

void LogoScene::Cleanup(){
	theTextureManager.UnloadTexture(logoFilename);
	delete logoSprite;
	logoSprite=NULL;
	cout<<"Logo eliminado"<<endl;
}


void LogoScene::ProcessEvent(const sf::Event &e){
	// si se presiona alguna tecla comienza el fundido para finalizar la escena
	if((e.Type == sf::Event::KeyPressed || e.Type == sf::Event::MouseButtonPressed) && totalElapsedTime<fadeTime + logoTime){
		totalElapsedTime = fadeTime + logoTime;
	}
}


void LogoScene::Update(const float &dt){

	theEngine.GetRenderWindow().SetView(vista);
	totalElapsedTime += dt;
	// se calcula la transparencia del logo segun en que etapa de la escena se encuentre (fundido de entrada, mostrando el logo, o fundido de salida)
	float alpha;
	if (totalElapsedTime<fadeTime){
		alpha = (totalElapsedTime/fadeTime);
	}else if(totalElapsedTime>=fadeTime && totalElapsedTime<fadeTime+logoTime){
		alpha = 1;
	}else if(totalElapsedTime<=fadeTime*2+logoTime){
		alpha = 1-((totalElapsedTime-logoTime-fadeTime)/fadeTime);
	}else{
		alpha = 0;
		EndScene();
	}
	logoSprite->SetColor(sf::Color(255.0f, 255.0f, 255.0f, alpha*255.0f));

	logoSprite->Animate(dt);
}


void LogoScene::Render(sf::RenderWindow &w){
	w.Clear(backgroundColor);
	w.Draw(*logoSprite);
}

